from flask import Blueprint, request, jsonify, current_app
from werkzeug.exceptions import BadRequest
from app.models.weather import WeatherData

history_weather_bp = Blueprint('history_weather', __name__)


@history_weather_bp.route('/get_historical_data_by_year', methods=['GET'])
def get_historical_weather_by_year():
    """获取历史天气数据"""
    try:
        # 获取查询参数
        year = request.args.get('year')
        fields = request.args.get('fields')
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 366))

        # 验证 year 格式
        if year and not year.isdigit():
            raise BadRequest('year 必须是数字')

        # 验证 fields 格式
        if fields:
            fields = fields.split(',')
            valid_fields = ['guilin_temp', 'guilin_max', 'guilin_min', 'guilin_dewp', 'guilin_mxspd',
                            'guilin_prcp','guilin_slp', 'guilin_visib', 'guilin_wdsp', 'hezhou_max',
                            'hezhou_min', 'liuzhou_max', 'liuzhou_min', 'record_date']
            for field in fields:
                if field not in valid_fields:
                    raise BadRequest(f'不支持的字段: {field}')

        # 构建查询
        query = WeatherData.query

        if year:
            query = query.filter(WeatherData.year == int(year))

        # 分页
        paginated_data = query.order_by(WeatherData.record_date.desc()).paginate(
            page=page, per_page=page_size, error_out=False
        )

        # 序列化数据
        data = []
        for item in paginated_data.items:
            item_dict = item.to_dict()
            if fields:
                if 'record_date' not in fields:
                    fields.append('record_date')
                selected_data = {field: item_dict[field] for field in fields}
            else:
                selected_data = {
                    "guilin_dewp": item_dict["guilin_dewp"],
                    "guilin_max": item_dict["guilin_max"],
                    "guilin_min": item_dict["guilin_min"],
                    "guilin_mxspd": item_dict["guilin_mxspd"],
                    "guilin_prcp": item_dict["guilin_prcp"],
                    "guilin_slp": item_dict["guilin_slp"],
                    "guilin_temp": item_dict["guilin_temp"],
                    "guilin_visib": item_dict["guilin_visib"],
                    "guilin_wdsp": item_dict["guilin_wdsp"],
                    "hezhou_max": item_dict["hezhou_max"],
                    "hezhou_min": item_dict["hezhou_min"],
                    "id": item_dict["id"],
                    "liuzhou_max": item_dict["liuzhou_max"],
                    "liuzhou_min": item_dict["liuzhou_min"],
                    "record_date": item_dict["record_date"]
                }
            data.append(selected_data)

        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': data,
            'pagination': {
                'page': paginated_data.page,
                'page_size': paginated_data.per_page,
                'total_pages': paginated_data.pages,
                'total_count': paginated_data.total
            }
        })

    except BadRequest as e:
        current_app.logger.warning(f"查询参数错误: {str(e)}")
        return jsonify({'code': 400, 'message': str(e)}), 400
    except Exception as e:
        current_app.logger.error(f'查询历史天气数据异常: {str(e)}')
        return jsonify({'code': 500, 'message': '服务器内部错误'}), 500


@history_weather_bp.route('/get_historical_data_by_year_and_month', methods=['GET'])
def get_historical_weather_by_year_and_month():
    """获取历史天气数据"""
    try:
        # 获取查询参数
        year = request.args.get('year')
        month = request.args.get('month')
        fields = request.args.get('fields')
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 31))

        # 验证 year 格式
        if year and not year.isdigit():
            raise BadRequest('year 必须是数字')

        # 验证 month 格式
        if month and not month.isdigit():
            raise BadRequest('month 必须是数字')

        # 验证 year 和 month 同时存在或同时不存在
        if (year and not month) or (month and not year):
            raise BadRequest('year 和 month 必须同时提供')

        # 验证 fields 格式
        if fields:
            fields = fields.split(',')
            valid_fields = ['guilin_dewp', 'guilin_max', 'guilin_min', 'guilin_mxspd', 'guilin_prcp',
                            'guilin_slp', 'guilin_temp', 'guilin_visib', 'guilin_wdsp', 'hezhou_max',
                            'hezhou_min', 'id', 'liuzhou_max', 'liuzhou_min', 'record_date']
            for field in fields:
                if field not in valid_fields:
                    raise BadRequest(f'不支持的字段: {field}')

        # 构建查询
        query = WeatherData.query

        # 正确的查询条件构建方式
        if year and month:
            query = query.filter(
                WeatherData.year == int(year),
                WeatherData.month == int(month)
            )

        # 分页
        paginated_data = query.order_by(WeatherData.record_date.desc()).paginate(
            page=page, per_page=page_size, error_out=False
        )

        # 序列化数据
        data = []
        for item in paginated_data.items:
            item_dict = item.to_dict()
            if fields:
                if 'record_date' not in fields:
                    fields.append('record_date')
                selected_data = {field: item_dict[field] for field in fields}
            else:
                selected_data = {
                    "guilin_dewp": item_dict["guilin_dewp"],
                    "guilin_max": item_dict["guilin_max"],
                    "guilin_min": item_dict["guilin_min"],
                    "guilin_mxspd": item_dict["guilin_mxspd"],
                    "guilin_prcp": item_dict["guilin_prcp"],
                    "guilin_slp": item_dict["guilin_slp"],
                    "guilin_temp": item_dict["guilin_temp"],
                    "guilin_visib": item_dict["guilin_visib"],
                    "guilin_wdsp": item_dict["guilin_wdsp"],
                    "hezhou_max": item_dict["hezhou_max"],
                    "hezhou_min": item_dict["hezhou_min"],
                    "id": item_dict["id"],
                    "liuzhou_max": item_dict["liuzhou_max"],
                    "liuzhou_min": item_dict["liuzhou_min"],
                    "record_date": item_dict["record_date"]
                }
            data.append(selected_data)

        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': data,
            'pagination': {
                'page': paginated_data.page,
                'page_size': paginated_data.per_page,
                'total_pages': paginated_data.pages,
                'total_count': paginated_data.total
            }
        })

    except BadRequest as e:
        current_app.logger.warning(f"查询参数错误: {str(e)}")
        return jsonify({'code': 400, 'message': str(e)}), 400
    except Exception as e:
        current_app.logger.error(f'查询历史天气数据异常: {str(e)}')
        return jsonify({'code': 500, 'message': '服务器内部错误'}), 500


@history_weather_bp.route('/get_historical_data_all', methods=['GET'])
def get_historical_all():
    """获取历史天气数据"""
    try:
        # 获取查询参数
        fields = request.args.get('fields')
        page = int(request.args.get('page', 1))
        page_size_str = request.args.get('page_size')

        # 先获取记录总数
        total_count = WeatherData.query.count()

        if page_size_str:
            try:
                page_size = int(page_size_str)
                if page_size <= 0:
                    raise BadRequest('page_size 必须是正整数')
            except ValueError:
                raise BadRequest('page_size 必须是整数')
        else:
            if total_count <= 100:  # 假设记录总数小于等于100时，全部返回
                page_size = total_count
            else:
                page_size = 100  # 否则设置为100条一页

        # 验证 fields 格式
        if fields:
            fields = fields.split(',')
            valid_fields = ['guilin_dewp', 'guilin_max', 'guilin_min', 'guilin_mxspd', 'guilin_prcp',
                            'guilin_slp', 'guilin_temp', 'guilin_visib', 'guilin_wdsp', 'hezhou_max',
                            'hezhou_min', 'id', 'liuzhou_max', 'liuzhou_min', 'record_date']
            for field in fields:
                if field not in valid_fields:
                    raise BadRequest(f'不支持的字段: {field}')

        # 构建查询
        query = WeatherData.query
        query = query.filter()

        # 分页
        paginated_data = query.order_by(WeatherData.record_date.desc()).paginate(
            page=page, per_page=page_size, error_out=False
        )

        # 序列化数据
        data = []
        for item in paginated_data.items:
            item_dict = item.to_dict()
            if fields:
                if 'record_date' not in fields:
                    fields.append('record_date')
                selected_data = {field: item_dict[field] for field in fields}
            else:
                selected_data = {
                    "guilin_dewp": item_dict["guilin_dewp"],
                    "guilin_max": item_dict["guilin_max"],
                    "guilin_min": item_dict["guilin_min"],
                    "guilin_mxspd": item_dict["guilin_mxspd"],
                    "guilin_prcp": item_dict["guilin_prcp"],
                    "guilin_slp": item_dict["guilin_slp"],
                    "guilin_temp": item_dict["guilin_temp"],
                    "guilin_visib": item_dict["guilin_visib"],
                    "guilin_wdsp": item_dict["guilin_wdsp"],
                    "hezhou_max": item_dict["hezhou_max"],
                    "hezhou_min": item_dict["hezhou_min"],
                    "id": item_dict["id"],
                    "liuzhou_max": item_dict["liuzhou_max"],
                    "liuzhou_min": item_dict["liuzhou_min"],
                    "record_date": item_dict["record_date"]
                }
            data.append(selected_data)

        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': data,
            'pagination': {
                'page': paginated_data.page,
                'page_size': paginated_data.per_page,
                'total_pages': paginated_data.pages,
                'total_count': paginated_data.total
            }
        })

    except BadRequest as e:
        current_app.logger.warning(f"查询参数错误: {str(e)}")
        return jsonify({'code': 400, 'message': str(e)}), 400
    except Exception as e:
        current_app.logger.error(f'查询历史天气数据异常: {str(e)}')
        return jsonify({'code': 500, 'message': '服务器内部错误'}), 500


@history_weather_bp.route('/get_available_years', methods=['GET'])
def get_available_years():
    """获取数据库中存在的所有年份"""
    try:
        # 从数据库查询不重复的年份
        years = WeatherData.query.with_entities(
            WeatherData.year
        ).distinct().order_by(
            WeatherData.year.desc()
        ).all()

        # 提取年份值并转为列表
        year_list = [year[0] for year in years]

        return jsonify({
            'code': 200,
            'message': '查询成功',
            'data': year_list
        })

    except Exception as e:
        current_app.logger.error(f'获取年份列表异常: {str(e)}')
        return jsonify({'code': 500, 'message': '服务器内部错误'}), 500
